<?php


class InserOrder extends Connection{
	private $conn;

	public function __construct(){
		Connection::init();
		$this->conn = $this->getConnection();
	}
	public function execute($id,order $obj){



			$stmt = $this->conn->prepare("INSERT INTO `orders`( `shop_id`, `order_status_id`, `info`)
													VALUES (?,1,?)");

			$stmt->bindValue(1,$id,PDO::PARAM_INT);
			$stmt->bindValue(2,$obj->getDescription(),PDO::PARAM_STR);


			if (!$stmt->execute()){
				throw new Exception ("не мога да добавя поръчка");
			};
			$stmt = $this->conn->prepare("SELECT id
										FROM `orders`
										where `shop_id`= ? and `order_status_id` = 1
										order by id desc
										limit 1");
			$stmt->bindValue(1,$id,PDO::PARAM_INT);
			$stmt->execute();
			$order_id= (int)$stmt->fetchColumn();
			foreach( $obj->getStocks() as $stock){
				if ($stock->getPromoPrice() !=null){
					$price=$stock->getPromoPrice() ;
				} else {
					$price=$stock->getPrice();
				}
				$stmt = $this->conn->prepare("INSERT INTO `order_stocks`(`order_id`, `stock_id`, `quantity`, `price`)
													VALUES (?,?,?,?)");


				$stmt->bindValue(1,$order_id,PDO::PARAM_INT);
				$stmt->bindValue(2,$stock->getId(),PDO::PARAM_STR);
				$stmt->bindValue(3,$stock->getOrderQuantity(),PDO::PARAM_INT);
				$stmt->bindValue(4,$price,PDO::PARAM_INT);

				if (!$stmt->execute()){
					throw new Exception ("не мога да добавя поръчка");
				};
			}

	}

}
?>